home *** CD-ROM | disk | FTP | other *** search
/ Amiga Plus 2000 #5 / Amiga Plus CD - 2000 - No. 5.iso / Tools / Dev / lame_src / lame.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-01-01  |  45.1 KB  |  1,583 lines

  1. /*
  2.  *    LAME MP3 encoding engine
  3.  *
  4.  *    Copyright (c) 1999 Mark Taylor
  5.  *
  6.  * This library is free software; you can redistribute it and/or
  7.  * modify it under the terms of the GNU Library General Public
  8.  * License as published by the Free Software Foundation; either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * This library is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU
  14.  * Library General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU Library General Public
  17.  * License along with this library; if not, write to the
  18.  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19.  * Boston, MA 02111-1307, USA.
  20.  */
  21.  
  22.  
  23. #include <assert.h>
  24.  
  25.  
  26. #include "gtkanal.h"
  27. #include "lame.h"
  28. #include "util.h"
  29. #include "timestatus.h"
  30. #include "psymodel.h"
  31. #include "newmdct.h"
  32. #include "quantize.h"
  33. #include "quantize-pvt.h"
  34. #include "bitstream.h"
  35. #include "version.h"
  36. #include "VbrTag.h"
  37. #include "id3tag.h"
  38. #include "tables.h"
  39. #include "brhist.h"
  40. #include "get_audio.h"
  41.  
  42. #ifdef __riscos__
  43. #include "asmstuff.h"
  44. #endif
  45.  
  46.  
  47.  
  48.  
  49. /********************************************************************
  50.  *   initialize internal params based on data in gf
  51.  *   (globalflags struct filled in by calling program)
  52.  *
  53.  ********************************************************************/
  54. int lame_init_params(lame_global_flags *gfp)
  55. {
  56.   int i;
  57.   lame_internal_flags *gfc=gfp->internal_flags;
  58.  
  59.   gfc->lame_init_params_init=1;
  60.  
  61.   memset(&gfc->bs, 0, sizeof(Bit_stream_struc));
  62.   memset(&gfc->l3_side,0x00,sizeof(III_side_info_t));
  63.  
  64.   memset((char *) gfc->mfbuf, 0, sizeof(short)*2*MFSIZE);
  65.  
  66.   /* The reason for
  67.    *       int mf_samples_to_encode = ENCDELAY + 288;
  68.    * ENCDELAY = internal encoder delay.  And then we have to add 288
  69.    * because of the 50% MDCT overlap.  A 576 MDCT granule decodes to
  70.    * 1152 samples.  To synthesize the 576 samples centered under this granule
  71.    * we need the previous granule for the first 288 samples (no problem), and
  72.    * the next granule for the next 288 samples (not possible if this is last
  73.    * granule).  So we need to pad with 288 samples to make sure we can
  74.    * encode the 576 samples we are interested in.
  75.    */
  76.   gfc->mf_samples_to_encode = ENCDELAY+288;
  77.   gfc->mf_size=ENCDELAY-MDCTDELAY;  /* we pad input with this many 0's */
  78.  
  79.  
  80.   gfp->frameNum=0;
  81.   if (gfp->num_channels==1) {
  82.     gfp->mode = MPG_MD_MONO;
  83.   }
  84.   gfc->stereo=2;
  85.   if (gfp->mode == MPG_MD_MONO) gfc->stereo=1;
  86.  
  87.   if (gfp->silent) {
  88.    gfp->brhist_disp=0;  /* turn of VBR historgram */
  89.   }
  90.   if (gfp->VBR==vbr_off) {
  91.     gfp->brhist_disp=0;  /* turn of VBR historgram */
  92.   }
  93.   if (gfp->VBR!=vbr_off) {
  94.     gfp->free_format=0;  /* VBR cant mix with free format */
  95.   }
  96.  
  97.   if (gfp->VBR==vbr_off && gfp->brate==0) {
  98.     /* no bitrate or compression ratio specified, use 11 */
  99.     if (gfp->compression_ratio==0) gfp->compression_ratio=11;
  100.   }
  101.  
  102.  
  103.   /* find bitrate if user specify a compression ratio */
  104.   if (gfp->VBR==vbr_off && gfp->compression_ratio > 0) {
  105.     
  106.     if (gfp->out_samplerate==0) 
  107.       gfp->out_samplerate=validSamplerate(gfp->in_samplerate);   
  108.     
  109.     /* choose a bitrate for the output samplerate which achieves
  110.      * specifed compression ratio 
  111.      */
  112.     gfp->brate = 
  113.       gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->compression_ratio);
  114.  
  115.     /* we need the version for the bitrate table look up */
  116.     gfc->samplerate_index = SmpFrqIndex((long)gfp->out_samplerate, &gfp->version);
  117.     /* find the nearest allowed bitrate */
  118.     if (!gfp->free_format)
  119.       gfp->brate = FindNearestBitrate(gfp->brate,gfp->version,gfp->out_samplerate);
  120.   }
  121.   if (gfp->brate >= 320) gfp->VBR=vbr_off;  /* dont bother with VBR at 320kbs */
  122.  
  123.  
  124.  
  125.   /* set the output sampling rate, and resample options if necessary
  126.      samplerate = input sample rate
  127.      resamplerate = ouput sample rate
  128.   */
  129.   if (gfp->out_samplerate==0) {
  130.     /* user did not specify output sample rate */
  131.     gfp->out_samplerate=gfp->in_samplerate;   /* default */
  132.  
  133.  
  134.     /* if resamplerate is not valid, find a valid value */
  135.     gfp->out_samplerate = validSamplerate(gfp->out_samplerate);
  136.  
  137.     if (gfp->VBR==vbr_off && gfp->brate>0) {
  138.       /* check if user specified bitrate requires downsampling */
  139.       gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->brate);
  140.       if (gfp->compression_ratio > 13 ) {
  141.     /* automatic downsample, if possible */
  142.     gfp->out_samplerate = validSamplerate((10*1000L*gfp->brate)/(16*gfc->stereo));
  143.       }
  144.     }
  145.     if (gfp->VBR==vbr_abr) {
  146.       /* check if user specified bitrate requires downsampling */
  147.       gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->VBR_mean_bitrate_kbps);
  148.       if (gfp->compression_ratio > 13 ) {
  149.     /* automatic downsample, if possible */
  150.     gfp->out_samplerate = validSamplerate((10*1000L*gfp->VBR_mean_bitrate_kbps)/(16*gfc->stereo));
  151.       }
  152.     }
  153.   }
  154.  
  155.   gfc->mode_gr = (gfp->out_samplerate <= 24000) ? 1 : 2;  /* mode_gr = 2 */
  156.   gfp->encoder_delay = ENCDELAY;
  157.   gfp->framesize = gfc->mode_gr*576;
  158.   if (gfp->ogg) gfp->framesize = 1024;
  159.  
  160.  
  161.   gfc->resample_ratio=1;
  162.   if (gfp->out_samplerate != gfp->in_samplerate) 
  163.         gfc->resample_ratio = (FLOAT)gfp->in_samplerate/(FLOAT)gfp->out_samplerate;
  164.  
  165.   /* estimate total frames.  must be done after setting sampling rate so
  166.    * we know the framesize.  */
  167.   gfp->totalframes=0;
  168.   gfp->totalframes = 2+ gfp->num_samples/(gfc->resample_ratio*gfp->framesize);
  169.  
  170.  
  171.  
  172.   /* 44.1kHz at 56kbs/channel: compression factor of 12.6
  173.      44.1kHz at 64kbs/channel: compression factor of 11.025
  174.      44.1kHz at 80kbs/channel: compression factor of 8.82
  175.      22.05kHz at 24kbs:  14.7
  176.      22.05kHz at 32kbs:  11.025
  177.      22.05kHz at 40kbs:  8.82
  178.      16kHz at 16kbs:  16.0
  179.      16kHz at 24kbs:  10.7
  180.  
  181.      compression_ratio
  182.         11                                .70?
  183.         12                   sox resample .66
  184.         14.7                 sox resample .45
  185.  
  186.   */
  187.  
  188.   /* for VBR, take a guess at the compression_ratio. for example: */
  189.   /* VBR_q           compression       like
  190.                       4.4             320kbs/41khz
  191.      0-1              5.5             256kbs/41khz
  192.      2                7.3             192kbs/41khz
  193.      4                8.8             160kbs/41khz
  194.      6                11              128kbs/41khz
  195.      9                14.7             96kbs
  196.      for lower bitrates, downsample with --resample
  197.   */
  198.   if (gfp->VBR==vbr_mt || gfp->VBR==vbr_rh) {
  199.     gfp->compression_ratio = 5.0 + gfp->VBR_q;
  200.   }else
  201.   if (gfp->VBR==vbr_abr) {
  202.     gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->VBR_mean_bitrate_kbps);
  203.   }else{
  204.     gfp->compression_ratio = gfp->out_samplerate*16*gfc->stereo/(1000.0*gfp->brate);
  205.   }
  206.  
  207.  
  208.  
  209.   /* At higher quality (lower compression) use STEREO instead of JSTEREO.
  210.    * (unless the user explicitly specified a mode ) */
  211.   if ( (!gfp->mode_fixed) && (gfp->mode !=MPG_MD_MONO)) {
  212.     if (gfp->compression_ratio < 9 ) {
  213.       gfp->mode = MPG_MD_STEREO;
  214.     }
  215.   }
  216.  
  217.  
  218.   /****************************************************************/
  219.   /* if a filter has not been enabled, see if we should add one: */
  220.   /****************************************************************/
  221.   if (gfp->lowpassfreq == 0) {
  222.     /* If the user has not selected their own filter, add a lowpass
  223.      * filter based on the compression ratio.  Formula based on
  224.           44.1   /160    4.4x
  225.           44.1   /128    5.5x      keep all bands
  226.           44.1   /96kbs  7.3x      keep band 28
  227.           44.1   /80kbs  8.8x      keep band 25
  228.           44.1khz/64kbs  11x       keep band 21  22?
  229.  
  230.       16khz/24kbs  10.7x       keep band 21
  231.       22kHz/32kbs  11x         keep band ?
  232.       22kHz/24kbs  14.7x       keep band 16
  233.           16    16     16x         keep band 14
  234.     */
  235.  
  236.  
  237.     /* Should we use some lowpass filters? */
  238.     int band = 1+floor(.5 + 14-18*log(gfp->compression_ratio/16.0));
  239.     if (gfc->resample_ratio != 1) {
  240.       /* resampling.  if we are resampling, add lowpass at least 90% */
  241.       band = Min(band,29);
  242.     }
  243.  
  244.     if (band < 31) {
  245.       gfc->lowpass1 = band/31.0;
  246.       gfc->lowpass2 = band/31.0;
  247.     }
  248.   }
  249.  
  250.   /****************************************************************/
  251.   /* apply user driven filters*/
  252.   /****************************************************************/
  253.   if ( gfp->highpassfreq > 0 ) {
  254.     gfc->highpass1 = 2.0*gfp->highpassfreq/gfp->out_samplerate; /* will always be >=0 */
  255.     if ( gfp->highpasswidth >= 0 ) {
  256.       gfc->highpass2 = 2.0*(gfp->highpassfreq+gfp->highpasswidth)/gfp->out_samplerate;
  257.     } else {
  258.       /* 15% above on default */
  259.       /* gfc->highpass2 = 1.15*2.0*gfp->highpassfreq/gfp->out_samplerate;  */
  260.       gfc->highpass2 = 1.00*2.0*gfp->highpassfreq/gfp->out_samplerate; 
  261.     }
  262.   }
  263.  
  264.   if ( gfp->lowpassfreq > 0 ) {
  265.     gfc->lowpass2 = 2.0*gfp->lowpassfreq/gfp->out_samplerate; /* will always be >=0 */
  266.     if ( gfp->lowpasswidth >= 0 ) {
  267.       gfc->lowpass1 = 2.0*(gfp->lowpassfreq-gfp->lowpasswidth)/gfp->out_samplerate;
  268.       if ( gfc->lowpass1 < 0 ) { /* has to be >= 0 */
  269.     gfc->lowpass1 = 0;
  270.       }
  271.     } else {
  272.       /* 15% below on default */
  273.       /* gfc->lowpass1 = 0.85*2.0*gfp->lowpassfreq/gfp->out_samplerate;  */
  274.       gfc->lowpass1 = 1.00*2.0*gfp->lowpassfreq/gfp->out_samplerate;
  275.     }
  276.   }
  277.  
  278.  
  279.   /***************************************************************/
  280.   /* compute info needed for polyphase filter (filter type==0, default)   */
  281.   /***************************************************************/
  282.   {
  283.     int band,maxband,minband;
  284.  
  285.     FLOAT8 freq;
  286.     if (gfc->lowpass1 > 0) {
  287.       minband=999;
  288.       maxband=-1;
  289.       for (band=0;  band <=31 ; ++band) { 
  290.     freq = band/31.0;
  291.     gfc->amp_lowpass[band] = 1;
  292.     /* this band and above will be zeroed: */
  293.     if (freq >= gfc->lowpass2) {
  294.       gfc->lowpass_band= Min(gfc->lowpass_band,band);
  295.       gfc->amp_lowpass[band]=0;
  296.     }
  297.     if (gfc->lowpass1 < freq && freq < gfc->lowpass2) {
  298.           minband = Min(minband,band);
  299.           maxband = Max(maxband,band);
  300.       gfc->amp_lowpass[band] = cos((PI/2)*(gfc->lowpass1-freq)/(gfc->lowpass2-gfc->lowpass1));
  301.     }
  302.     /*
  303.     DEBUGF("lowpass band=%i  amp=%f \n",band,gfc->amp_lowpass[band]);
  304.     */
  305.       }
  306.       /* compute the *actual* transition band implemented by the polyphase filter */
  307.       if (minband==999) gfc->lowpass1 = (gfc->lowpass_band-.75)/31.0;
  308.       else gfc->lowpass1 = (minband-.75)/31.0;
  309.       gfc->lowpass2 = gfc->lowpass_band/31.0;
  310.       
  311.       gfc->lowpass_start_band = minband;
  312.       gfc->lowpass_end_band   = maxband;
  313.       
  314.       /* as the lowpass may have changed above
  315.        * calculate the amplification here again
  316.        */
  317.       for (band=minband;  band <=maxband; ++band) { 
  318.     freq = band/31.0;
  319.     gfc->amp_lowpass[band] = cos((PI/2)*(gfc->lowpass1-freq)/(gfc->lowpass2-gfc->lowpass1));
  320.       }
  321.     } else {
  322.       gfc->lowpass_start_band = 0;
  323.       gfc->lowpass_end_band   = -1;  /* do not to run into for-loops */
  324.     }
  325.  
  326.     /* make sure highpass filter is within 90% of what the effective highpass
  327.      * frequency will be */
  328.     if (gfc->highpass2 > 0) 
  329.       if (gfc->highpass2 <  .9*(.75/31.0) ) {
  330.     gfc->highpass1=0; gfc->highpass2=0;
  331.     MSGF("Warning: highpass filter disabled.  highpass frequency to small\n");
  332.       }
  333.     
  334.  
  335.     if (gfc->highpass2 > 0) {
  336.       minband=999;
  337.       maxband=-1;
  338.       for (band=0;  band <=31; ++band) { 
  339.     freq = band/31.0;
  340.     gfc->amp_highpass[band] = 1;
  341.     /* this band and below will be zereod */
  342.     if (freq <= gfc->highpass1) {
  343.       gfc->highpass_band = Max(gfc->highpass_band,band);
  344.       gfc->amp_highpass[band]=0;
  345.     }
  346.     if (gfc->highpass1 < freq && freq < gfc->highpass2) {
  347.           minband = Min(minband,band);
  348.           maxband = Max(maxband,band);
  349.       gfc->amp_highpass[band] = cos((PI/2)*(gfc->highpass2-freq)/(gfc->highpass2-gfc->highpass1));
  350.     }
  351.     /*    
  352.     DEBUGF("highpass band=%i  amp=%f \n",band,gfc->amp_highpass[band]);
  353.     */
  354.       }
  355.       /* compute the *actual* transition band implemented by the polyphase filter */
  356.       gfc->highpass1 = gfc->highpass_band/31.0;
  357.       if (maxband==-1) gfc->highpass2 = (gfc->highpass_band+.75)/31.0;
  358.       else gfc->highpass2 = (maxband+.75)/31.0;
  359.       
  360.       gfc->highpass_start_band = minband;
  361.       gfc->highpass_end_band   = maxband;
  362.  
  363.       /* as the highpass may have changed above
  364.        * calculate the amplification here again
  365.        */
  366.       for (band=minband;  band <=maxband; ++band) { 
  367.     freq = band/31.0;
  368.     gfc->amp_highpass[band] = cos((PI/2)*(gfc->highpass2-freq)/(gfc->highpass2-gfc->highpass1));
  369.       }
  370.     } else {
  371.       gfc->highpass_start_band = 0;
  372.       gfc->highpass_end_band   = -1;  /* do not to run into for-loops */
  373.     }
  374.     /*
  375.     DEBUGF("lowpass band with amp=0:  %i \n",gfc->lowpass_band);
  376.     DEBUGF("highpass band with amp=0:  %i \n",gfc->highpass_band);
  377.     DEBUGF("lowpass band start:  %i \n",gfc->lowpass_start_band);
  378.     DEBUGF("lowpass band end:    %i \n",gfc->lowpass_end_band);
  379.     DEBUGF("highpass band start:  %i \n",gfc->highpass_start_band);
  380.     DEBUGF("highpass band end:    %i \n",gfc->highpass_end_band);
  381.     */
  382.   }
  383.  
  384.  
  385.  
  386.   /***************************************************************/
  387.   /* compute info needed for FIR filter (filter_type==1) */
  388.   /***************************************************************/
  389.  
  390.  
  391.  
  392.  
  393.   gfc->mode_ext=MPG_MD_LR_LR;
  394.   gfc->stereo = (gfp->mode == MPG_MD_MONO) ? 1 : 2;
  395.  
  396.  
  397.   gfc->samplerate_index = SmpFrqIndex((long)gfp->out_samplerate, &gfp->version);
  398.   if( gfc->samplerate_index < 0) {
  399.     display_bitrates(stderr);
  400.     return -1;
  401.   }
  402.   if (gfp->free_format) {
  403.     gfc->bitrate_index=0;
  404.   }else{
  405.     if( (gfc->bitrate_index = BitrateIndex(gfp->brate, gfp->version,gfp->out_samplerate)) < 0) {
  406.       display_bitrates(stderr);
  407.       return -1;
  408.     }
  409.   }
  410.  
  411.  
  412.   /* choose a min/max bitrate for VBR */
  413.   if (gfp->VBR!=vbr_off) {
  414.     /* if the user didn't specify VBR_max_bitrate: */
  415.     if (0==gfp->VBR_max_bitrate_kbps) {
  416.       gfc->VBR_max_bitrate=14;   /* default: allow 320kbs */
  417.     }else{
  418.       if( (gfc->VBR_max_bitrate  = BitrateIndex(gfp->VBR_max_bitrate_kbps, gfp->version,gfp->out_samplerate)) < 0) {
  419.     display_bitrates(stderr);
  420.     return -1;
  421.       }
  422.     }
  423.     if (0==gfp->VBR_min_bitrate_kbps) {
  424.       gfc->VBR_min_bitrate=1;  /* 32 kbps */
  425.     }else{
  426.       if( (gfc->VBR_min_bitrate  = BitrateIndex(gfp->VBR_min_bitrate_kbps, gfp->version,gfp->out_samplerate)) < 0) {
  427.     display_bitrates(stderr);
  428.     return -1;
  429.       }
  430.     }
  431.     gfp->VBR_mean_bitrate_kbps = Min(bitrate_table[gfp->version][gfc->VBR_max_bitrate]*.95,gfp->VBR_mean_bitrate_kbps);
  432.     gfp->VBR_mean_bitrate_kbps = Max(bitrate_table[gfp->version][gfc->VBR_min_bitrate]*.95,gfp->VBR_mean_bitrate_kbps);
  433.     
  434.     /* Note: ABR mode should normally be used without a -V n setting,
  435.      * (or with the default value of 4)
  436.      * but the code below allows us to test how adjusting the maskings
  437.      * effects CBR encodings.  Lowering the maskings will make LAME
  438.      * work harder to get over=0 and may give better noise shaping?
  439.      */
  440.     if (gfp->VBR == vbr_abr)
  441.     {
  442.       static const FLOAT8 dbQ[10]={-5.0,-3.75,-2.5,-1.25,0,0.4,0.8,1.2,1.6,2.0};
  443.       FLOAT8 masking_lower_db;
  444.       assert( gfp->VBR_q <= 9 );
  445.       assert( gfp->VBR_q >= 0 );
  446.       masking_lower_db = dbQ[gfp->VBR_q];
  447.       gfc->masking_lower = pow(10.0,masking_lower_db/10);
  448.       gfc->ATH_lower = (4-gfp->VBR_q)*4.0; 
  449.     }
  450.     
  451.     /* - lower masking depending on Quality setting
  452.      * - quality control together with adjusted ATH MDCT scaling
  453.      *   on lower quality setting allocate more noise from
  454.      *   ATH masking, and on higher quality setting allocate
  455.      *   less noise from ATH masking.
  456.      * - experiments show that going more than 2dB over GPSYCHO's
  457.      *   limits ends up in very annoying artefacts
  458.      */
  459.     if (gfp->VBR == vbr_rh)
  460.     {
  461.       static const FLOAT8 dbQ[10]={-5.0,-3.75,-2.5,-1.25,0,0.4,0.8,1.2,1.6,2.0};
  462.       FLOAT8 masking_lower_db;
  463.       assert( gfp->VBR_q <= 9 );
  464.       assert( gfp->VBR_q >= 0 );
  465.       masking_lower_db = dbQ[gfp->VBR_q];
  466.       gfc->masking_lower = pow(10.0,masking_lower_db/10);
  467.       gfc->ATH_lower = (4-gfp->VBR_q)*4.0;     
  468.     }
  469.  
  470.  
  471.  
  472.   }
  473.  
  474.   /* VBR needs at least the output of GPSYCHO,
  475.    * so we have to garantee that by setting a minimum 
  476.    * quality level, actually level 7 does it.
  477.    * the -v and -V x settings switch the quality to level 2
  478.    * you would have to add a -f or -q 5 to reduce the quality
  479.    * down to level 7 or 5
  480.    */
  481.   if (gfp->VBR!=vbr_off) gfp->quality=Min(gfp->quality,7);
  482.   /* dont allow forced mid/side stereo for mono output */
  483.   if (gfp->mode == MPG_MD_MONO) gfp->force_ms=0;
  484.  
  485.  
  486.   /* Do not write VBR tag if VBR flag is not specified */
  487.   if (gfp->VBR==vbr_off) gfp->bWriteVbrTag=0;
  488.   if (gfp->ogg) gfp->bWriteVbrTag=0;
  489.   if (gfp->gtkflag) gfp->bWriteVbrTag=0;
  490.  
  491.   /* some file options not allowed if output is: not specified or stdout */
  492.  
  493.   if (gfp->outPath!=NULL && gfp->outPath[0]=='-' ) {
  494.     gfp->bWriteVbrTag=0; /* turn off VBR tag */
  495.   }
  496.  
  497.   if (gfp->outPath==NULL || gfp->outPath[0]=='-' ) {
  498.     gfp->id3tag_used=0;         /* turn of id3 tagging */
  499.   }
  500.  
  501.  
  502.  
  503.   if (gfc->pinfo != NULL) {
  504.     gfp->bWriteVbrTag=0;  /* disable Xing VBR tag */
  505.   }
  506.  
  507.   init_bit_stream_w(gfc);
  508.  
  509.  
  510.   /* set internal feature flags.  USER should not access these since
  511.    * some combinations will produce strange results */
  512.  
  513.   /* no psymodel, no noise shaping */
  514.   if (gfp->quality==9) {
  515.     gfc->filter_type=0;
  516.     gfc->psymodel=0;
  517.     gfc->quantization=0;
  518.     gfc->noise_shaping=0;
  519.     gfc->noise_shaping_stop=0;
  520.     gfc->use_best_huffman=0;
  521.   }
  522.  
  523.   if (gfp->quality==8) gfp->quality=7;
  524.  
  525.   /* use psymodel (for short block and m/s switching), but no noise shapping */
  526.   if (gfp->quality==7) {
  527.     gfc->filter_type=0;
  528.     gfc->psymodel=1;
  529.     gfc->quantization=0;
  530.     gfc->noise_shaping=0;
  531.     gfc->noise_shaping_stop=0;
  532.     gfc->use_best_huffman=0;
  533.   }
  534.  
  535.   if (gfp->quality==6) gfp->quality=5;
  536.  
  537.   if (gfp->quality==5) {
  538.     /* the default */
  539.     gfc->filter_type=0;
  540.     gfc->psymodel=1;
  541.     gfc->quantization=0;
  542.     gfc->noise_shaping=1;
  543.     gfc->noise_shaping_stop=0;
  544.     gfc->use_best_huffman=0;
  545.   }
  546.  
  547.   if (gfp->quality==4) gfp->quality=2;
  548.  
  549.   if (gfp->quality==3) {
  550.     gfc->filter_type=0;
  551.     gfc->psymodel=1;
  552.     gfc->quantization=1;
  553.     gfc->noise_shaping=1;
  554.     gfc->noise_shaping_stop=0;
  555.     gfc->use_best_huffman=1;
  556.   }
  557.  
  558.   if (gfp->quality==2) {
  559.     gfc->filter_type=0;
  560.     gfc->psymodel=1;
  561.     gfc->quantization=1;
  562.     if (gfp->VBR==vbr_mt || gfp->VBR==vbr_rh)
  563.       /* VBR modes currently have some problems which are aggravated by 
  564.        * scalefac_scale */
  565.       gfc->noise_shaping=1;
  566.     else
  567.       gfc->noise_shaping=2;
  568.     gfc->noise_shaping_stop=0;
  569.     gfc->use_best_huffman=1;
  570.   }
  571.  
  572.   if (gfp->quality==1) {
  573.     gfc->filter_type=0;
  574.     gfc->psymodel=1;
  575.     gfc->quantization=1;
  576.     gfc->noise_shaping=2;
  577.     gfc->noise_shaping_stop=0;
  578.     gfc->use_best_huffman=1;
  579.   }
  580.  
  581.   if (gfp->quality==0) {
  582.     /* 0..1 quality */
  583.     gfc->filter_type=1;         /* not yet coded */
  584.     gfc->psymodel=1;
  585.     gfc->quantization=1;
  586.     gfc->noise_shaping=3;       /* not yet coded */
  587.     gfc->noise_shaping_stop=2;  /* not yet coded */
  588.     gfc->use_best_huffman=2;   /* not yet coded */
  589.     return -1;
  590.   }
  591.  
  592.  
  593.   for (i = 0; i < SBMAX_l + 1; i++) {
  594.     gfc->scalefac_band.l[i] =
  595.       sfBandIndex[gfc->samplerate_index + (gfp->version * 3) + 
  596.              6*(gfp->out_samplerate<16000)].l[i];
  597.   }
  598.   for (i = 0; i < SBMAX_s + 1; i++) {
  599.     gfc->scalefac_band.s[i] =
  600.       sfBandIndex[gfc->samplerate_index + (gfp->version * 3) + 
  601.              6*(gfp->out_samplerate<16000)].s[i];
  602.   }
  603.  
  604.  
  605.   /* determine the mean bitrate for main data */
  606.   gfc->sideinfo_len = 4;
  607.   if ( gfp->version == 1 )
  608.     {   /* MPEG 1 */
  609.       if ( gfc->stereo == 1 )
  610.     gfc->sideinfo_len += 17;
  611.       else
  612.     gfc->sideinfo_len += 32;
  613.     }
  614.   else
  615.     {   /* MPEG 2 */
  616.       if ( gfc->stereo == 1 )
  617.     gfc->sideinfo_len += 9;
  618.       else
  619.     gfc->sideinfo_len += 17;
  620.     }
  621.   
  622.   if (gfp->error_protection) gfc->sideinfo_len += 2;
  623.   
  624.  
  625.   if (gfp->bWriteVbrTag)
  626.     {
  627.       /* Write initial VBR Header to bitstream */
  628.       InitVbrTag(gfp);
  629.     }
  630.  
  631.   if (gfp->brhist_disp)
  632.     brhist_init(gfp,1,14);
  633.  
  634. #ifdef HAVEVORBIS
  635.   if (gfp->ogg) {
  636.     lame_encode_ogg_init(gfp);
  637.     gfc->filter_type=-1;   /* vorbis claims not to need filters */
  638.     gfp->VBR=vbr_off;            /* ignore lame's various VBR modes */
  639.   }
  640. #endif
  641.  
  642.   return 0;
  643. }
  644.  
  645.  
  646.  
  647.  
  648.  
  649.  
  650.  
  651.  
  652.  
  653. /************************************************************************
  654.  *
  655.  * print_config
  656.  *
  657.  * PURPOSE:  Prints the encoding parameters used
  658.  *
  659.  ************************************************************************/
  660. void lame_print_config(lame_global_flags *gfp)
  661. {
  662.   lame_internal_flags *gfc=gfp->internal_flags;
  663.  
  664.   static const char *mode_names[4] = { "stereo", "j-stereo", "dual-ch", "single-ch" };
  665.   FLOAT out_samplerate=gfp->out_samplerate/1000.0;
  666.   FLOAT in_samplerate = gfc->resample_ratio*out_samplerate;
  667.  
  668.   lame_print_version(stderr);
  669.   if (gfp->num_channels==2 && gfc->stereo==1) {
  670.     MSGF("Autoconverting from stereo to mono. Setting encoding to mono mode.\n");
  671.   }
  672.   if (gfc->resample_ratio!=1) {
  673.     MSGF("Resampling:  input=%.1fkHz  output=%.1fkHz\n",
  674.         in_samplerate,out_samplerate);
  675.   }
  676.   if (gfc->filter_type==0) {
  677.   if (gfc->highpass2>0.0)
  678.     MSGF("Using polyphase highpass filter, transition band: %.0f Hz -  %.0f Hz\n",
  679.         gfc->highpass1*out_samplerate*500,
  680.         gfc->highpass2*out_samplerate*500);
  681.   if (gfc->lowpass1>0.0)
  682.     MSGF("Using polyphase lowpass filter,  transition band:  %.0f Hz - %.0f Hz\n",
  683.         gfc->lowpass1*out_samplerate*500,
  684.         gfc->lowpass2*out_samplerate*500);
  685.   }
  686.  
  687.   if (gfp->gtkflag) {
  688.     MSGF("Analyzing %s \n",gfp->inPath);
  689.   }
  690.   else {
  691.     MSGF("Encoding %s to %s\n",
  692.         (strcmp(gfp->inPath, "-")? gfp->inPath : "stdin"),
  693.         (strcmp(gfp->outPath, "-")? gfp->outPath : "stdout"));
  694.     if (gfp->ogg) {
  695.       MSGF("Encoding as %.1f kHz VBR Ogg Vorbis \n",
  696.           gfp->out_samplerate/1000.0);
  697.     }else
  698.     if (gfp->VBR==vbr_mt || gfp->VBR==vbr_rh)
  699.       MSGF("Encoding as %.1f kHz VBR(q=%i) %s MPEG%i LayerIII (%4.1fx estimated) qval=%i\n",
  700.           gfp->out_samplerate/1000.0,
  701.           gfp->VBR_q,mode_names[gfp->mode],2-gfp->version,gfp->compression_ratio,gfp->quality);
  702.     else
  703.     if (gfp->VBR==vbr_abr)
  704.       MSGF("Encoding as %.1f kHz average %d kbps %s MPEG%i LayerIII (%4.1fx) qval=%i\n",
  705.           gfp->out_samplerate/1000.0,
  706.           gfp->VBR_mean_bitrate_kbps,mode_names[gfp->mode],2-gfp->version,gfp->compression_ratio,gfp->quality);
  707.     else {
  708.       MSGF("Encoding as %.1f kHz %d kbps %s MPEG%i LayerIII (%4.1fx)  qval=%i\n",
  709.           gfp->out_samplerate/1000.0,gfp->brate,
  710.           mode_names[gfp->mode],2-gfp->version,gfp->compression_ratio,gfp->quality);
  711.     }
  712.   }
  713.   if (gfp->free_format) {
  714.     MSGF("Warning: many decoders cannot handle free format bitstreams\n");
  715.     if (gfp->brate>320) {
  716.       MSGF("Warning: many decoders cannot handle free format bitrates > 320kbs\n");
  717.     }
  718.   }
  719.  
  720.   fflush(stderr);
  721. }
  722.  
  723.  
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.  
  731.  
  732.  
  733.  
  734. /************************************************************************
  735. *
  736. * encodeframe()           Layer 3
  737. *
  738. * encode a single frame
  739. *
  740. ************************************************************************
  741. lame_encode_frame()
  742.  
  743.  
  744.                        gr 0            gr 1
  745. inbuf:           |--------------|---------------|-------------|
  746. MDCT output:  |--------------|---------------|-------------|
  747.  
  748. FFT's                    <---------1024---------->
  749.                                          <---------1024-------->
  750.  
  751.  
  752.  
  753.     inbuf = buffer of PCM data size=MP3 framesize
  754.     encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY
  755.     so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]
  756.  
  757.     psy-model FFT has a 1 granule day, so we feed it data for the next granule.
  758.     FFT is centered over granule:  224+576+224
  759.     So FFT starts at:   576-224-MDCTDELAY
  760.  
  761.     MPEG2:  FFT ends at:  BLKSIZE+576-224-MDCTDELAY
  762.     MPEG1:  FFT ends at:  BLKSIZE+2*576-224-MDCTDELAY    (1904)
  763.  
  764.     FFT starts at 576-224-MDCTDELAY (304)  = 576-FFTOFFSET
  765.  
  766. */
  767.  
  768. int lame_encode_mp3_frame(lame_global_flags *gfp,
  769. short int inbuf_l[],short int inbuf_r[],
  770. char *mp3buf, int mp3buf_size)
  771. {
  772.   FLOAT8 xr[2][2][576];
  773.   int l3_enc[2][2][576];
  774.   int mp3count;
  775.   III_psy_ratio masking_ratio[2][2];    /*LR ratios */
  776.   III_psy_ratio masking_MS_ratio[2][2]; /*MS ratios */
  777.   III_psy_ratio (*masking)[2][2];  /*LR ratios and MS ratios*/
  778.   III_scalefac_t scalefac[2][2];
  779.   short int *inbuf[2];
  780.   lame_internal_flags *gfc=gfp->internal_flags;
  781.  
  782.  
  783.   typedef FLOAT8 pedata[2][2];
  784.   pedata pe,pe_MS;
  785.   pedata *pe_use;
  786.  
  787.   int ch,gr,mean_bits;
  788.   int bitsPerFrame;
  789.  
  790.   int check_ms_stereo;
  791.   FLOAT8 ms_ratio_next=0;
  792.   FLOAT8 ms_ratio_prev=0;
  793.  
  794.   memset((char *) masking_ratio, 0, sizeof(masking_ratio));
  795.   memset((char *) masking_MS_ratio, 0, sizeof(masking_MS_ratio));
  796.   memset((char *) scalefac, 0, sizeof(scalefac));
  797.   inbuf[0]=inbuf_l;
  798.   inbuf[1]=inbuf_r;
  799.     
  800.   gfc->mode_ext = MPG_MD_LR_LR;
  801.  
  802.   if (gfc->lame_encode_frame_init==0 )  {
  803. #if 0
  804.     /* Figure average number of 'slots' per frame. */
  805.     FLOAT8 avg_slots_per_frame;
  806.     FLOAT8 sampfreq =   gfp->out_samplerate/1000.0;
  807.     int bit_rate = gfp->brate;
  808.  
  809.     avg_slots_per_frame = (bit_rate*gfp->framesize) /
  810.       (sampfreq* 8);
  811.     /* -f fast-math option causes some strange rounding here, be carefull: */
  812.     gfc->frac_SpF  = avg_slots_per_frame - floor(avg_slots_per_frame + 1e-9);
  813.     if (fabs(gfc->frac_SpF) < 1e-9) gfc->frac_SpF = 0;
  814.     gfc->slot_lag  = -gfc->frac_SpF;
  815.     gfc->padding = 1;
  816.     if (gfc->frac_SpF==0) gfc->padding = 0;
  817. #else
  818.     /* padding method as described in 
  819.      * "MPEG-Layer3 / Bitstream Syntax and Decoding"
  820.      * by Martin Sieler, Ralph Sperschneider
  821.      *
  822.      * note: there is no padding for the very first frame
  823.      *
  824.      * Robert.Hegemann@gmx.de 2000-06-22
  825.      */
  826.         
  827.     gfc->difference = ((gfp->version+1)*72000L*gfp->brate) % gfp->out_samplerate;
  828.     gfc->remainder  = gfc->difference;
  829. #endif    
  830.     
  831.     gfc->lame_encode_frame_init=1;
  832.     
  833.     /* check FFT will not use a negative starting offset */
  834.     assert(576>=FFTOFFSET);
  835.     /* check if we have enough data for FFT */
  836.     assert(gfc->mf_size>=(BLKSIZE+gfp->framesize-FFTOFFSET));
  837.     /* check if we have enough data for polyphase filterbank */
  838.     /* it needs 1152 samples + 286 samples ignored for one granule */
  839.     /*          1152+576+286 samples for two granules */
  840.     assert(gfc->mf_size>=(286+576*(1+gfc->mode_gr)));
  841.  
  842.     /* prime the MDCT/polyphase filterbank with a short block */
  843.     { 
  844.       int i,j;
  845.       short primebuff0[286+1152+576];
  846.       short primebuff1[286+1152+576];
  847.       for (i=0, j=0; i<286+576*(1+gfc->mode_gr); ++i) {
  848.     if (i<576*gfc->mode_gr) {
  849.       primebuff0[i]=0;
  850.       if (gfc->stereo) 
  851.         primebuff1[i]=0;
  852.     }else{
  853.       primebuff0[i]=inbuf[0][j];
  854.       if (gfc->stereo) 
  855.         primebuff1[i]=inbuf[1][j];
  856.       ++j;
  857.     }
  858.       }
  859.       /* polyphase filtering / mdct */
  860.       for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
  861.     for ( ch = 0; ch < gfc->stereo; ch++ ) {
  862.       gfc->l3_side.gr[gr].ch[ch].tt.block_type=SHORT_TYPE;
  863.     }
  864.       }
  865.       mdct_sub48(gfp,primebuff0, primebuff1, xr, &gfc->l3_side);
  866.     }
  867.   }
  868.  
  869.  
  870.   /********************** padding *****************************/
  871.   switch (gfp->padding_type) {
  872.   case 0:
  873.     gfc->padding=0;
  874.     break;
  875.   case 1:
  876.     gfc->padding=1;
  877.     break;
  878.   case 2:
  879.   default:
  880.     if (gfp->VBR!=vbr_off) {
  881.       gfc->padding=0;
  882.     } else {
  883.       if (gfp->disable_reservoir) {
  884.     gfc->padding = 0;
  885.     /* if the user specified --nores, dont very gfc->padding either */
  886.     /* tiny changes in frac_SpF rounding will cause file differences */
  887.       }else{
  888. #if 0
  889.     if (gfc->frac_SpF != 0) {
  890.       if (gfc->slot_lag > (gfc->frac_SpF-1.0) ) {
  891.         gfc->slot_lag -= gfc->frac_SpF;
  892.         gfc->padding = 0;
  893.         DEBUGF("%i padding = 0 \n",gfp->frameNum);
  894.  
  895.       }
  896.       else {
  897.         gfc->padding = 1;
  898.         gfc->slot_lag += (1-gfc->frac_SpF);
  899.       }
  900.     }
  901. #else
  902.         /* padding method as described in 
  903.          * "MPEG-Layer3 / Bitstream Syntax and Decoding"
  904.          * by Martin Sieler, Ralph Sperschneider
  905.          *
  906.          * note: there is no padding for the very first frame
  907.          *
  908.          * Robert.Hegemann@gmx.de 2000-06-22
  909.          */
  910.  
  911.         gfc->remainder -= gfc->difference;
  912.         if (gfc->remainder < 0)
  913.           {
  914.             gfc->remainder += gfp->out_samplerate;
  915.             gfc->padding = 1;
  916.           }
  917.         else
  918.           {
  919.             gfc->padding = 0;
  920.           }
  921. #endif
  922.       } /* reservoir enabled */
  923.     }
  924.   }
  925.  
  926.  
  927.   /********************** status display  *****************************/
  928.   if (!gfp->gtkflag && !gfp->silent) {
  929.     int mod = gfp->version == 0 ? 100 : 50;
  930.     if (gfp->frameNum%mod==0) {
  931.       timestatus(gfp->out_samplerate,gfp->frameNum,gfp->totalframes,gfp->framesize);
  932.  
  933.       if (gfp->brhist_disp)
  934.       brhist_disp(gfp->totalframes);
  935.  
  936.     }
  937.   }
  938.  
  939.   if (gfc->psymodel) {
  940.     /* psychoacoustic model
  941.      * psy model has a 1 granule (576) delay that we must compensate for
  942.      * (mt 6/99).
  943.      */
  944.     int ret;
  945.     short int *bufp[2];  /* address of beginning of left & right granule */
  946.     int blocktype[2];
  947.  
  948.     ms_ratio_prev=gfc->ms_ratio[gfc->mode_gr-1];
  949.     for (gr=0; gr < gfc->mode_gr ; gr++) {
  950.  
  951.       for ( ch = 0; ch < gfc->stereo; ch++ )
  952.     bufp[ch] = &inbuf[ch][576 + gr*576-FFTOFFSET];
  953.  
  954.       ret=L3psycho_anal( gfp,bufp, gr, 
  955.              &gfc->ms_ratio[gr],&ms_ratio_next,&gfc->ms_ener_ratio[gr],
  956.              masking_ratio, masking_MS_ratio,
  957.              pe[gr],pe_MS[gr],blocktype);
  958.       if (ret!=0) return -4;
  959.  
  960.       for ( ch = 0; ch < gfc->stereo; ch++ )
  961.     gfc->l3_side.gr[gr].ch[ch].tt.block_type=blocktype[ch];
  962.  
  963.     }
  964.   }else{
  965.     for (gr=0; gr < gfc->mode_gr ; gr++)
  966.       for ( ch = 0; ch < gfc->stereo; ch++ ) {
  967.     gfc->l3_side.gr[gr].ch[ch].tt.block_type=NORM_TYPE;
  968.     pe[gr][ch]=700;
  969.       }
  970.   }
  971.  
  972.  
  973.   /* block type flags */
  974.   for( gr = 0; gr < gfc->mode_gr; gr++ ) {
  975.     for ( ch = 0; ch < gfc->stereo; ch++ ) {
  976.       gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
  977.       cod_info->mixed_block_flag = 0;     /* never used by this model */
  978.       if (cod_info->block_type == NORM_TYPE )
  979.     cod_info->window_switching_flag = 0;
  980.       else
  981.     cod_info->window_switching_flag = 1;
  982.     }
  983.   }
  984.  
  985.  
  986.   /* polyphase filtering / mdct */
  987.   mdct_sub48(gfp,inbuf[0], inbuf[1], xr, &gfc->l3_side);
  988.   /* re-order the short blocks, for more efficient encoding below */
  989.   for (gr = 0; gr < gfc->mode_gr; gr++) {
  990.     for (ch = 0; ch < gfc->stereo; ch++) {
  991.       gr_info *cod_info = &gfc->l3_side.gr[gr].ch[ch].tt;
  992.       if (cod_info->block_type==SHORT_TYPE) {
  993.     freorder(gfc->scalefac_band.s,xr[gr][ch]);
  994.       }
  995.     }
  996.   }
  997.   
  998.  
  999.  
  1000.  
  1001.  
  1002.   /* use m/s gfc->stereo? */
  1003.   check_ms_stereo =  (gfp->mode == MPG_MD_JOINT_STEREO);
  1004.   if (check_ms_stereo) {
  1005.     /* make sure block type is the same in each channel */
  1006.     check_ms_stereo =
  1007.       (gfc->l3_side.gr[0].ch[0].tt.block_type==gfc->l3_side.gr[0].ch[1].tt.block_type) &&
  1008.       (gfc->l3_side.gr[1].ch[0].tt.block_type==gfc->l3_side.gr[1].ch[1].tt.block_type);
  1009.   }
  1010.   if (check_ms_stereo) {
  1011.     /* ms_ratio = is like the ratio of side_energy/total_energy */
  1012.     FLOAT8 ms_ratio_ave;
  1013.     /*     ms_ratio_ave = .5*(ms_ratio[0] + ms_ratio[1]);*/
  1014.     ms_ratio_ave = .25*(gfc->ms_ratio[0] + gfc->ms_ratio[1]+
  1015.              ms_ratio_prev + ms_ratio_next);
  1016.     if ( (ms_ratio_ave <.35) && (.5*(gfc->ms_ratio[0]+gfc->ms_ratio[1])<.45) )
  1017.          gfc->mode_ext = MPG_MD_MS_LR;
  1018.   }
  1019.   if (gfp->force_ms) gfc->mode_ext = MPG_MD_MS_LR;
  1020.  
  1021.  
  1022.  
  1023.   if (gfp->gtkflag && gfc->pinfo != NULL) {
  1024.     for ( gr = 0; gr < gfc->mode_gr; gr++ ) {
  1025.       for ( ch = 0; ch < gfc->stereo; ch++ ) {
  1026.     gfc->pinfo->ms_ratio[gr]=gfc->ms_ratio[gr];
  1027.     gfc->pinfo->ms_ener_ratio[gr]=gfc->ms_ener_ratio[gr];
  1028.     gfc->pinfo->blocktype[gr][ch]=
  1029.       gfc->l3_side.gr[gr].ch[ch].tt.block_type;
  1030.     memcpy(gfc->pinfo->xr[gr][ch],xr[gr][ch],sizeof(xr[gr][ch]));
  1031.     /* if MS stereo, switch to MS psy data */
  1032.     if (gfc->mode_ext==MPG_MD_MS_LR) {
  1033.       gfc->pinfo->pe[gr][ch]=gfc->pinfo->pe[gr][ch+2];
  1034.       gfc->pinfo->ers[gr][ch]=gfc->pinfo->ers[gr][ch+2];
  1035.       memcpy(gfc->pinfo->energy[gr][ch],gfc->pinfo->energy[gr][ch+2],
  1036.          sizeof(gfc->pinfo->energy[gr][ch]));
  1037.     }
  1038.       }
  1039.     }
  1040.   }
  1041.  
  1042.  
  1043.  
  1044.  
  1045.   /* bit and noise allocation */
  1046.   if (MPG_MD_MS_LR == gfc->mode_ext) {
  1047.     masking = &masking_MS_ratio;    /* use MS masking */
  1048.     pe_use=&pe_MS;
  1049.   } else {
  1050.     masking = &masking_ratio;    /* use LR masking */
  1051.     pe_use=&pe;
  1052.   }
  1053.  
  1054.  
  1055.   switch (gfp->VBR){ 
  1056.   default:
  1057.   case vbr_off:
  1058.     iteration_loop( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1059.     break;
  1060.   case vbr_mt:
  1061.     VBR_quantize( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1062.     break;
  1063.   case vbr_rh:
  1064.     VBR_iteration_loop( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1065.     break;
  1066.   case vbr_abr:
  1067.     ABR_iteration_loop( gfp,*pe_use, gfc->ms_ener_ratio, xr, *masking, l3_enc, scalefac);
  1068.     break;
  1069.   }
  1070.  
  1071.   /* update VBR histogram data */
  1072.   brhist_add_count(gfc->bitrate_index);
  1073.  
  1074.   /*  write the frame to the bitstream  */
  1075.   getframebits(gfp,&bitsPerFrame,&mean_bits);
  1076.  
  1077.   format_bitstream( gfp, bitsPerFrame, l3_enc, scalefac);
  1078.  
  1079.   /* copy mp3 bit buffer into array */
  1080.   mp3count = copy_buffer(mp3buf,mp3buf_size,&gfc->bs);
  1081.  
  1082.   if (gfp->bWriteVbrTag) AddVbrFrame(gfp);
  1083.  
  1084.  
  1085.   if (gfp->gtkflag && gfc->pinfo != NULL) {
  1086.     int j;
  1087.     for ( ch = 0; ch < gfc->stereo; ch++ ) {
  1088.       for ( j = 0; j < FFTOFFSET; j++ )
  1089.     gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j+gfp->framesize];
  1090.       for ( j = FFTOFFSET; j < 1600; j++ ) {
  1091.     gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j-FFTOFFSET];
  1092.       }
  1093.     }
  1094.   }
  1095.  
  1096.   gfp->frameNum++;
  1097.   return mp3count;
  1098. }
  1099.  
  1100.  
  1101. /* routine to feed exactly one frame (gfp->framesize) worth of data to the 
  1102. encoding engine.  All buffering, resampling, etc, handled by calling
  1103. program.  
  1104. */
  1105. int lame_encode_frame(lame_global_flags *gfp,
  1106. short int inbuf_l[],short int inbuf_r[],
  1107. char *mp3buf, int mp3buf_size)
  1108. {
  1109.   if (gfp->ogg) {
  1110. #ifdef HAVEVORBIS
  1111.     return lame_encode_ogg_frame(gfp,inbuf_l,inbuf_r,mp3buf,mp3buf_size);
  1112. #else
  1113.     return -5; /* wanna encode ogg without vorbis */
  1114. #endif
  1115.   } else {
  1116.     return lame_encode_mp3_frame(gfp,inbuf_l,inbuf_r,mp3buf,mp3buf_size);
  1117.   }
  1118. }
  1119.  
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.  
  1127.  
  1128.  
  1129.  
  1130.  
  1131. /*
  1132.  * THE MAIN LAME ENCODING INTERFACE
  1133.  * mt 3/00
  1134.  *
  1135.  * input pcm data, output (maybe) mp3 frames.
  1136.  * This routine handles all buffering, resampling and filtering for you.
  1137.  * The required mp3buffer_size can be computed from num_samples,
  1138.  * samplerate and encoding rate, but here is a worst case estimate:
  1139.  *
  1140.  * mp3buffer_size in bytes = 1.25*num_samples + 7200
  1141.  *
  1142.  * return code = number of bytes output in mp3buffer.  can be 0
  1143. */
  1144. int lame_encode_buffer(lame_global_flags *gfp,
  1145.    short int buffer_l[], short int buffer_r[],int nsamples,
  1146.    char *mp3buf, int mp3buf_size)
  1147. {
  1148.   int mp3size=0,ret=0,i,ch,mf_needed;
  1149.   lame_internal_flags *gfc=gfp->internal_flags;
  1150.   short int *mfbuf[2];
  1151.   short int *in_buffer[2];
  1152.   in_buffer[0] = buffer_l;
  1153.   in_buffer[1] = buffer_r;
  1154.  
  1155.   if (!gfc->lame_init_params_init) return -3;
  1156.  
  1157.   /* some sanity checks */
  1158.   assert(ENCDELAY>=MDCTDELAY);
  1159.   assert(BLKSIZE-FFTOFFSET >= 0);
  1160.   mf_needed = BLKSIZE+gfp->framesize-FFTOFFSET;  /* ammount needed for FFT */
  1161.   mf_needed = Max(mf_needed,286+576*(1+gfc->mode_gr)); /* ammount needed for MDCT/filterbank */
  1162.   assert(MFSIZE>=mf_needed);
  1163.  
  1164.   mfbuf[0]=gfc->mfbuf[0];
  1165.   mfbuf[1]=gfc->mfbuf[1];
  1166.  
  1167.   if (gfp->num_channels==2  && gfc->stereo==1) {
  1168.     /* downsample to mono */
  1169.     for (i=0; i<nsamples; ++i) {
  1170.       in_buffer[0][i]=((int)in_buffer[0][i]+(int)in_buffer[1][i])/2;
  1171.       in_buffer[1][i]=0;
  1172.     }
  1173.   }
  1174.  
  1175.  
  1176.   while (nsamples > 0) {
  1177.     int n_in=0;
  1178.     int n_out=0;
  1179.     /* copy in new samples into mfbuf, with filtering */
  1180.  
  1181.     for (ch=0; ch<gfc->stereo; ch++) {
  1182.       if (gfc->resample_ratio>1)  {
  1183.     n_out=fill_buffer_downsample(gfp,&mfbuf[ch][gfc->mf_size],gfp->framesize,
  1184.                       in_buffer[ch],nsamples,&n_in,ch);
  1185.       } else if (gfc->resample_ratio<1) {
  1186.     n_out=fill_buffer_upsample(gfp,&mfbuf[ch][gfc->mf_size],gfp->framesize,
  1187.                       in_buffer[ch],nsamples,&n_in,ch);
  1188.       } else {
  1189.     n_out=Min(gfp->framesize,nsamples);
  1190.     n_in = n_out;
  1191.     memcpy( (char *) &mfbuf[ch][gfc->mf_size],(char *)in_buffer[ch],sizeof(short int)*n_out);
  1192.       }
  1193.       in_buffer[ch] += n_in;
  1194.     }
  1195.  
  1196.     nsamples -= n_in;
  1197.     gfc->mf_size += n_out;
  1198.     assert(gfc->mf_size<=MFSIZE);
  1199.     gfc->mf_samples_to_encode += n_out;
  1200.  
  1201.  
  1202.     if (gfc->mf_size >= mf_needed) {
  1203.       /* encode the frame.  */
  1204.       ret = lame_encode_frame(gfp,mfbuf[0],mfbuf[1],mp3buf,mp3buf_size);
  1205.  
  1206.       if (ret < 0) return ret;
  1207.       mp3buf += ret;
  1208.       mp3size += ret;
  1209.  
  1210.       /* shift out old samples */
  1211.       gfc->mf_size -= gfp->framesize;
  1212.       gfc->mf_samples_to_encode -= gfp->framesize;
  1213.       for (ch=0; ch<gfc->stereo; ch++)
  1214.     for (i=0; i<gfc->mf_size; i++)
  1215.       mfbuf[ch][i]=mfbuf[ch][i+gfp->framesize];
  1216.     }
  1217.   }
  1218.   assert(nsamples==0);
  1219.  
  1220.   return mp3size;
  1221. }
  1222.  
  1223.  
  1224.  
  1225.  
  1226. int lame_encode_buffer_interleaved(lame_global_flags *gfp,
  1227.    short int buffer[], int nsamples, char *mp3buf, int mp3buf_size)
  1228. {
  1229.   int mp3size=0,ret=0,i,ch,mf_needed;
  1230.   lame_internal_flags *gfc=gfp->internal_flags;
  1231.   short int *mfbuf[2];
  1232.  
  1233.   if (!gfc->lame_init_params_init) return -3;
  1234.  
  1235.   mfbuf[0]=gfc->mfbuf[0];
  1236.   mfbuf[1]=gfc->mfbuf[1];
  1237.  
  1238.   /* some sanity checks */
  1239.   assert(ENCDELAY>=MDCTDELAY);
  1240.   assert(BLKSIZE-FFTOFFSET >= 0);
  1241.   mf_needed = BLKSIZE+gfp->framesize-FFTOFFSET;
  1242.   assert(MFSIZE>=mf_needed);
  1243.  
  1244.   if (gfp->num_channels == 1) {
  1245.     return lame_encode_buffer(gfp,buffer, NULL ,nsamples,mp3buf,mp3buf_size);
  1246.   }
  1247.  
  1248.   if (gfc->resample_ratio!=1)  {
  1249.     short int *buffer_l;
  1250.     short int *buffer_r;
  1251.     buffer_l=malloc(sizeof(short int)*nsamples);
  1252.     buffer_r=malloc(sizeof(short int)*nsamples);
  1253.     if (buffer_l == NULL || buffer_r == NULL) {
  1254.       return -2;
  1255.     }
  1256.     for (i=0; i<nsamples; i++) {
  1257.       buffer_l[i]=buffer[2*i];
  1258.       buffer_r[i]=buffer[2*i+1];
  1259.     }
  1260.     ret = lame_encode_buffer(gfp,buffer_l,buffer_r,nsamples,mp3buf,mp3buf_size);
  1261.     free(buffer_l);
  1262.     free(buffer_r);
  1263.     return ret;
  1264.   }
  1265.  
  1266.  
  1267.   if (gfp->num_channels==2  && gfc->stereo==1) {
  1268.     /* downsample to mono */
  1269.     for (i=0; i<nsamples; ++i) {
  1270.       buffer[2*i]=((int)buffer[2*i]+(int)buffer[2*i+1])/2;
  1271.       buffer[2*i+1]=0;
  1272.     }
  1273.   }
  1274.  
  1275.  
  1276.   while (nsamples > 0) {
  1277.     int n_out;
  1278.     /* copy in new samples */
  1279.     n_out = Min(gfp->framesize,nsamples);
  1280.     for (i=0; i<n_out; ++i) {
  1281.       mfbuf[0][gfc->mf_size+i]=buffer[2*i];
  1282.       mfbuf[1][gfc->mf_size+i]=buffer[2*i+1];
  1283.     }
  1284.     buffer += 2*n_out;
  1285.  
  1286.     nsamples -= n_out;
  1287.     gfc->mf_size += n_out;
  1288.     assert(gfc->mf_size<=MFSIZE);
  1289.     gfc->mf_samples_to_encode += n_out;
  1290.  
  1291.     if (gfc->mf_size >= mf_needed) {
  1292.       /* encode the frame */
  1293.       ret = lame_encode_frame(gfp,mfbuf[0],mfbuf[1],mp3buf,mp3buf_size);
  1294.       if (ret < 0) {
  1295.     /* fatel error: mp3buffer was too small */
  1296.     return ret;
  1297.       }
  1298.       mp3buf += ret;
  1299.       mp3size += ret;
  1300.  
  1301.       /* shift out old samples */
  1302.       gfc->mf_size -= gfp->framesize;
  1303.       gfc->mf_samples_to_encode -= gfp->framesize;
  1304.       for (ch=0; ch<gfc->stereo; ch++)
  1305.     for (i=0; i<gfc->mf_size; i++)
  1306.       mfbuf[ch][i]=mfbuf[ch][i+gfp->framesize];
  1307.     }
  1308.   }
  1309.   assert(nsamples==0);
  1310.   return mp3size;
  1311. }
  1312.  
  1313.  
  1314.  
  1315.  
  1316. /* old LAME interface.  use lame_encode_buffer instead */
  1317. int lame_encode(lame_global_flags *gfp, short int in_buffer[2][1152],char *mp3buf,int size){
  1318.   int imp3;
  1319.   lame_internal_flags *gfc=gfp->internal_flags;
  1320.   if (!gfc->lame_init_params_init) return -3;
  1321.   imp3= lame_encode_buffer(gfp,in_buffer[0],in_buffer[1],gfp->framesize,mp3buf,size);
  1322.   return imp3;
  1323. }
  1324.  
  1325.  
  1326. /*****************************************************************/
  1327. /* flush internal mp3 buffers,                                   */
  1328. /*****************************************************************/
  1329. int lame_encode_finish(lame_global_flags *gfp,char *mp3buffer, int mp3buffer_size)
  1330. {
  1331.   int imp3=0,mp3count,mp3buffer_size_remaining;
  1332.   short int buffer[2][1152];
  1333.   lame_internal_flags *gfc=gfp->internal_flags;
  1334.  
  1335.   memset((char *)buffer,0,sizeof(buffer));
  1336.   mp3count = 0;
  1337.  
  1338.   while (gfc->mf_samples_to_encode > 0) {
  1339.  
  1340.     mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1341.  
  1342.     /* if user specifed buffer size = 0, dont check size */
  1343.     if (mp3buffer_size == 0) mp3buffer_size_remaining=0;  
  1344.  
  1345.     /* send in a frame of 0 padding until all internal sample buffers flushed */
  1346.     imp3=lame_encode_buffer(gfp,buffer[0],buffer[1],gfp->framesize,mp3buffer,mp3buffer_size_remaining);
  1347.     /* dont count the above padding: */
  1348.     gfc->mf_samples_to_encode -= gfp->framesize;
  1349.  
  1350.     if (imp3 < 0) {
  1351.       /* some type of fatel error */
  1352.       freegfc(gfc);    
  1353.       return imp3;
  1354.     }
  1355.     mp3buffer += imp3;
  1356.     mp3count += imp3;
  1357.   }
  1358.  
  1359.  
  1360.   gfp->frameNum--;
  1361.   if (!gfp->gtkflag && !gfp->silent) {
  1362.       timestatus(gfp->out_samplerate,gfp->frameNum,gfp->totalframes,gfp->framesize);
  1363.  
  1364.       if (gfp->brhist_disp)
  1365.     {
  1366.       brhist_disp(gfp->totalframes);
  1367.       brhist_disp_total(gfp);
  1368.     }
  1369.  
  1370.       timestatus_finish();
  1371.   }
  1372.  
  1373.   mp3buffer_size_remaining = mp3buffer_size - mp3count;
  1374.   /* if user specifed buffer size = 0, dont check size */
  1375.   if (mp3buffer_size == 0) mp3buffer_size_remaining=0;  
  1376.  
  1377.   if (gfp->ogg) {
  1378. #ifdef HAVEVORBIS    
  1379.     /* ogg related stuff */
  1380.     imp3 = lame_encode_ogg_finish(gfp,mp3buffer,mp3buffer_size_remaining);
  1381. #endif
  1382.   }else{
  1383.     /* mp3 related stuff.  bit buffer might still contain some data */
  1384.     flush_bitstream(gfp);
  1385.     imp3= copy_buffer(mp3buffer,mp3buffer_size_remaining,&gfc->bs);
  1386.   }
  1387.   if (imp3 < 0) {
  1388.     freegfc(gfc);    
  1389.     return imp3;
  1390.   }
  1391.   mp3count += imp3;
  1392.  
  1393.   freegfc(gfc);    
  1394.   return mp3count;
  1395. }
  1396.  
  1397.  
  1398. /*****************************************************************/
  1399. /* write VBR Xing header, and ID3 tag, if asked for               */
  1400. /*****************************************************************/
  1401. void lame_mp3_tags(lame_global_flags *gfp)
  1402. {
  1403.   if (gfp->bWriteVbrTag)
  1404.     {
  1405.       /* Calculate relative quality of VBR stream
  1406.        * 0=best, 100=worst */
  1407.       int nQuality=gfp->VBR_q*100/9;
  1408.       /* Write Xing header again */
  1409.       PutVbrTag(gfp,gfp->outPath,nQuality);
  1410.     }
  1411.  
  1412.  
  1413.   /* write an ID3 tag  */
  1414.   if(gfp->id3tag_used) {
  1415.     id3_buildtag(&gfp->id3tag);
  1416.     id3_writetag(gfp->outPath, &gfp->id3tag);
  1417.   }
  1418. }
  1419.  
  1420.  
  1421. void lame_version(lame_global_flags *gfp,char *ostring) {
  1422.   strncpy(ostring,get_lame_version(),20);
  1423. }
  1424.  
  1425.  
  1426.  
  1427.  
  1428.  
  1429.  
  1430.  
  1431. /* initialize mp3 encoder */
  1432. int lame_init(lame_global_flags *gfp)
  1433. {
  1434.   lame_internal_flags *gfc;
  1435.  
  1436.   /*
  1437.    *  Disable floating point exepctions
  1438.    */
  1439. #ifdef __FreeBSD__
  1440. # include <floatingpoint.h>
  1441.   {
  1442.   /* seet floating point mask to the Linux default */
  1443.   fp_except_t mask;
  1444.   mask=fpgetmask();
  1445.   /* if bit is set, we get SIGFPE on that error! */
  1446.   fpsetmask(mask & ~(FP_X_INV|FP_X_DZ));
  1447.   /*  DEBUGF("FreeBSD mask is 0x%x\n",mask); */
  1448.   }
  1449. #endif
  1450. #if defined(__riscos__) && !defined(ABORTFP)
  1451.   /* Disable FPE's under RISC OS */
  1452.   /* if bit is set, we disable trapping that error! */
  1453.   /*   _FPE_IVO : invalid operation */
  1454.   /*   _FPE_DVZ : divide by zero */
  1455.   /*   _FPE_OFL : overflow */
  1456.   /*   _FPE_UFL : underflow */
  1457.   /*   _FPE_INX : inexact */
  1458.   DisableFPETraps( _FPE_IVO | _FPE_DVZ | _FPE_OFL );
  1459. #endif
  1460.  
  1461.  
  1462.   /*
  1463.    *  Debugging stuff
  1464.    *  The default is to ignore FPE's, unless compiled with -DABORTFP
  1465.    *  so add code below to ENABLE FPE's.
  1466.    */
  1467.  
  1468. #if defined(ABORTFP) 
  1469. #if defined(_MSC_VER)
  1470.   {
  1471.     #include <float.h>
  1472.     unsigned int mask;
  1473.     mask=_controlfp( 0, 0 );
  1474.     mask&=~(_EM_OVERFLOW|_EM_UNDERFLOW|_EM_ZERODIVIDE|_EM_INVALID);
  1475.     mask=_controlfp( mask, _MCW_EM );
  1476.     }
  1477. #elif defined(__CYGWIN__)
  1478. #  define _FPU_GETCW(cw) __asm__ ("fnstcw %0" : "=m" (*&cw))
  1479. #  define _FPU_SETCW(cw) __asm__ ("fldcw %0" : : "m" (*&cw))
  1480.  
  1481. #  define _EM_INEXACT     0x00000001 /* inexact (precision) */
  1482. #  define _EM_UNDERFLOW   0x00000002 /* underflow */
  1483. #  define _EM_OVERFLOW    0x00000004 /* overflow */
  1484. #  define _EM_ZERODIVIDE  0x00000008 /* zero divide */
  1485. #  define _EM_INVALID     0x00000010 /* invalid */
  1486.   {
  1487.     unsigned int mask;
  1488.     _FPU_GETCW(mask);
  1489.     /* Set the FPU control word to abort on most FPEs */
  1490.     mask &= ~(_EM_UNDERFLOW | _EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID);
  1491.     _FPU_SETCW(mask);
  1492.   }
  1493. # elif (defined(__linux__) || defined(__FreeBSD__))
  1494.   {
  1495. #  include <fpu_control.h>
  1496. #  ifndef _FPU_GETCW
  1497. #  define _FPU_GETCW(cw) __asm__ ("fnstcw %0" : "=m" (*&cw))
  1498. #  endif
  1499. #  ifndef _FPU_SETCW
  1500. #  define _FPU_SETCW(cw) __asm__ ("fldcw %0" : : "m" (*&cw))
  1501. #  endif
  1502.     unsigned int mask;
  1503.     _FPU_GETCW(mask);
  1504.     /* Set the Linux mask to abort on most FPE's */
  1505.     /* if bit is set, we _mask_ SIGFPE on that error! */
  1506.     /*  mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM | _FPU_MASK_UM );*/
  1507.     mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM );
  1508.     _FPU_SETCW(mask);
  1509.   }
  1510. #endif
  1511. #endif /* ABORTFP */
  1512.  
  1513.  
  1514.  
  1515.   memset(gfp,0,sizeof(lame_global_flags));
  1516.   if (NULL==(gfp->internal_flags = malloc(sizeof(lame_internal_flags))))
  1517.     return -1;
  1518.   gfc=(lame_internal_flags *) gfp->internal_flags;
  1519.   memset(gfc,0,sizeof(lame_internal_flags));
  1520.  
  1521.   /* Global flags.  set defaults here */
  1522.   gfp->mode = MPG_MD_JOINT_STEREO;
  1523.   gfp->mode_fixed=0;
  1524.   gfp->force_ms=0;
  1525.   gfp->brate=0;
  1526.   gfp->copyright=0;
  1527.   gfp->original=1;
  1528.   gfp->extension=0;
  1529.   gfp->error_protection=0;
  1530.   gfp->emphasis=0;
  1531.   gfp->in_samplerate=1000*44.1;
  1532.   gfp->out_samplerate=0;
  1533.   gfp->num_channels=2;
  1534.   gfp->num_samples=MAX_U_32_NUM;
  1535.  
  1536.   gfp->allow_diff_short=0;
  1537.   gfp->ATHonly=0;
  1538.   gfp->noATH=0;
  1539.   gfp->bWriteVbrTag=1;
  1540.   gfp->cwlimit=0;
  1541.   gfp->disable_reservoir=0;
  1542.   gfp->experimentalX = 0;
  1543.   gfp->experimentalY = 0;
  1544.   gfp->experimentalZ = 0;
  1545.   gfp->gtkflag=0;
  1546.   gfp->quality=5;
  1547.   gfp->input_format=sf_unknown;
  1548.  
  1549.   gfp->lowpassfreq=0;
  1550.   gfp->highpassfreq=0;
  1551.   gfp->lowpasswidth=-1;
  1552.   gfp->highpasswidth=-1;
  1553.  
  1554.   gfp->no_short_blocks=0;
  1555.   gfp->padding_type=2;
  1556.   gfp->swapbytes=0;
  1557.   gfp->silent=1;
  1558.   gfp->VBR=vbr_off;
  1559.   gfp->VBR_q=4;
  1560.   gfp->VBR_mean_bitrate_kbps=128;
  1561.   gfp->VBR_min_bitrate_kbps=0;
  1562.   gfp->VBR_max_bitrate_kbps=0;
  1563.   gfp->VBR_hard_min=0;
  1564.  
  1565.   gfc->pcmbitwidth = 16;
  1566.   gfc->resample_ratio=1;
  1567.   gfc->lowpass_band=32;
  1568.   gfc->highpass_band=-1;
  1569.   gfc->VBR_min_bitrate=1;
  1570.   gfc->VBR_max_bitrate=13;
  1571.  
  1572.   gfc->OldValue[0]=180;
  1573.   gfc->OldValue[1]=180;
  1574.   gfc->CurrentStep=4;
  1575.   gfc->masking_lower=1;
  1576.  
  1577.  
  1578.  
  1579.   return 0;
  1580. }
  1581.  
  1582.  
  1583.